// pages/cart/cart.js
const common = require('../../utils/util.js')
const app = getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        editStatus: 0,
        cartList: [],
        totalNum: 0,
        totalPrice: 0,
        servicePrice: 0,
        actualPrice: 0,
        allSelect: 0,
        cartIdList: '',
        cartSelectList: [],
        userInfo: {},
        // x轴方向的偏移
        x: [],
        // 当前x的值
        currentX: []
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        this.getUserInfo()
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {
        this.getCartList()
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {
        this.setData({
            editStatus: 0,
            cartList: [],
            totalNum: 0,
            totalPrice: 0,
            servicePrice: 0,
            actualPrice: 0,
            allSelect: 0,
            cartIdList: '',
            cartSelectList: [],
            // x轴方向的偏移
            x: [],
            // 当前x的值
            currentX: []
        })
        this.getCartList()
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {

    },

    getUserInfo: function() {
        const that = this
        let data = {}
        common.post('User/user_info', data).then(function(res) {
            if (res.code == 204) {
                that.setData({
                    userInfo: {}
                })
            } else {
                that.setData({
                    userInfo: res
                })
            }
        }).catch(function(e) {})
    },

    getCartList: function() {
        wx.showLoading({
            title: '加载中',
        })
        const that = this
        let data = {
            client: 2
        }
        common.post('Cart/cart_list', data).then(function(res) {
            wx.hideLoading()
            if (res.code == 204) {
                that.setData({
                    cartList: []
                })
                that.calPrice()
            } else {
                that.setData({
                    cartList: res
                })
                that.calPrice()
            }
        }).catch(function(e) {})
    },

    goodsNumAdd: function(e) {
        const that = this
        let goodsNum = e.currentTarget.dataset.num
        let cartList = this.data.cartList
        goodsNum++
        cartList.forEach(function(items) {
            items.goods_sku.forEach(function(item) {
                if (item.cart_id == e.currentTarget.dataset.id) {
                    item.num = goodsNum
                    let data = {
                        cart_id: item.cart_id,
                        num: goodsNum
                    }
                    common.post('Cart/cart_num', data).then(function(res) {
                        that.setData({
                            cartList: cartList
                        })
                        that.calPrice()
                    }).catch(function(e) {})
                }
            })
        })
    },

    goodsNumMinus: function(e) {
        const that = this
        let goodsNum = e.currentTarget.dataset.num
        let cartList = this.data.cartList
        if (goodsNum > 1) {
            goodsNum--
            cartList.forEach(function(items) {
                items.goods_sku.forEach(function(item) {
                    if (item.cart_id == e.currentTarget.dataset.id) {
                        item.num = goodsNum
                        let data = {
                            cart_id: item.cart_id,
                            num: goodsNum
                        }
                        common.post('Cart/cart_num', data).then(function(res) {
                            that.setData({
                                cartList: cartList
                            })
                            that.calPrice()
                        }).catch(function(e) {})
                    }
                })
            })
        }
    },

    cartEdit: function() {
        if (this.data.editStatus == 0) {
            this.setData({
                editStatus: 1
            })
        } else {
            this.setData({
                editStatus: 0
            })
        }
    },

    goodsClick: function(e) {
        const that = this
        if (e.detail == 0) {
            let data = {
                cart_id: e.currentTarget.dataset.id
            }
            common.post('Cart/cart_select', data).then(function(res) {
                let cartList = that.data.cartList
                cartList.forEach(function(items) {
                    items.goods_sku.forEach(function(item) {
                        if (item.cart_id == e.currentTarget.dataset.id) {
                            item.selected = 1
                        }
                    })
                })
                that.setData({
                    cartList: cartList
                })
                that.calPrice()
            }).catch(function(e) {})
        } else {
            let data = {
                cart_id: e.currentTarget.dataset.id,
                delete: 1
            }
            common.post('Cart/cart_select', data).then(function(res) {
                let cartList = that.data.cartList
                cartList.forEach(function(items) {
                    items.goods_sku.forEach(function(item) {
                        if (item.cart_id == e.currentTarget.dataset.id) {
                            item.selected = 0
                        }
                    })
                })
                that.setData({
                    cartList: cartList
                })
                that.calPrice()
            }).catch(function(e) {})
        }
    },

    shopClick: function(e) {
        const that = this
        let cartList = this.data.cartList
        if (e.detail == 0) {
            cartList.forEach(function(items) {
                if (items.store_id == e.currentTarget.dataset.id) {
                    items.goods_sku.forEach(function(item) {
                        item.selected = 1
                        let data = {
                            cart_id: item.cart_id
                        }
                        common.post('Cart/cart_select', data).then(function(res) {}).catch(function(e) {})
                    })
                }
            })
            that.setData({
                cartList: cartList
            })
            that.calPrice()
        } else {
            cartList.forEach(function(items) {
                if (items.store_id == e.currentTarget.dataset.id) {
                    items.goods_sku.forEach(function(item) {
                        item.selected = 0
                        let data = {
                            cart_id: item.cart_id,
                            delete: 1
                        }
                        common.post('Cart/cart_select', data).then(function(res) {}).catch(function(e) {})
                    })
                }
            })
            that.setData({
                cartList: cartList
            })
            that.calPrice()
        }
    },

    allClick: function(e) {
        const that = this
        let cartList = this.data.cartList
        if (e.detail == 0) {
            cartList.forEach(function(items) {
                items.goods_sku.forEach(function(item) {
                    item.selected = 1
                    let data = {
                        cart_id: item.cart_id
                    }
                    common.post('Cart/cart_select', data).then(function(res) {}).catch(function(e) {})
                })
            })
            that.setData({
                cartList: cartList
            })
            that.calPrice()
        } else {
            cartList.forEach(function(items) {
                items.goods_sku.forEach(function(item) {
                    item.selected = 0
                    let data = {
                        cart_id: item.cart_id,
                        delete: 1
                    }
                    common.post('Cart/cart_select', data).then(function(res) {}).catch(function(e) {})
                })
            })
            that.setData({
                cartList: cartList
            })
            that.calPrice()
        }
    },

    calPrice: function() {
        let cartList = this.data.cartList
        let totalPrice = 0
        let servicePrice = 0
        let actualPrice = 0
        let totalNum = 0
        let cartIdList = ''
        cartList.forEach(function(items) {
            if (items.goods_sku.findIndex(function(e) {
                    return e.selected == 0
                }) == -1) {
                items.selected = 1
            } else {
                items.selected = 0
            }
            items.goods_sku.forEach(function(item) {
                if (item.selected == 1) {
                    cartIdList += item.cart_id + ','
                    totalPrice += item.price * item.num
                    totalNum += 1
                    if (item.type == 1) {
                        actualPrice += item.price * item.num
                    } else if (item.type == 2) {
                        servicePrice += item.self_price * item.num
                        actualPrice += item.self_price * item.num
                    } else if (item.type == 3) {
                        actualPrice += item.retail_price * item.num
                    }
                    else if(item.type == 9){
                        actualPrice += item.retail_price * item.num
                    }
                }
            })
        })
        if (cartList.length > 0 && cartList.findIndex(function(e) {
                return e.selected == 0
            }) == -1) {
            this.setData({
                allSelect: 1
            })
        } else {
            this.setData({
                allSelect: 0
            })
        }
        cartIdList = cartIdList.substr(0, cartIdList.length - 1)
        this.setData({
            cartList: cartList,
            totalPrice: totalPrice,
            servicePrice: servicePrice,
            actualPrice: actualPrice,
            totalNum: totalNum,
            cartIdList: cartIdList
        })
    },

    goOrderConfirm: function() {
        let freeNum = 0
        let cartSelectList = []
        let cartList = this.data.cartList
        cartList.forEach(function(items) {
            if (items.goods_sku.findIndex(function(e) {
                    return e.selected == 1
                }) > -1) {
                let datas = {
                    store_id: items.store_id,
                    store_name: items.store_name,
                    goods_sku: []
                }
                items.goods_sku.forEach(function(item) {
                    if (item.selected == 1) {
                        datas.goods_sku.push(item)
                    }
                })
                cartSelectList = cartSelectList.concat(datas)
            }
        })
        if (cartSelectList.length == 0) {
            wx.showToast({
                title: '请选择商品',
                icon: 'none',
                duration: 1000
            })
        } else if (cartSelectList.length > 1) {
            wx.showToast({
                title: '暂不支持同时结算不同店铺商品',
                icon: 'none',
                duration: 1000
            })
        } else {
            cartSelectList.forEach(function(items) {
                items.goods_sku.forEach(function(item) {
                    if (item.type == 2) {
                        freeNum += item.num
                    }
                })
            })
            if (freeNum > this.data.userInfo.buy_num) {
                wx.showModal({
                    title: '提示',
                    content: '本月剩余' + this.data.userInfo.buy_num + '可用白领次数,请重新选择',
                    success(res) {

                    }
                })
            } else {
                wx.setStorageSync('actualPrice', this.data.actualPrice)
                // wx.setStorageSync('servicePrice', this.data.servicePrice)
                // wx.setStorageSync('totalPrice', this.data.totalPrice)
                wx.setStorageSync('cartIdList', this.data.cartIdList)
                wx.setStorageSync('cartSelectList', cartSelectList)
                wx.setStorageSync('isVipGoods', 1)
                wx.navigateTo({
                    url: '/pages/order/orderConfirm/orderConfirm'
                })
            }
        }

    },

    goDelete: function() {
        const that = this
        let data = {
            cart_id: this.data.cartIdList
        }
        common.post('Cart/cart_delet', data).then(function(res) {
            that.getCartList()
        }).catch(function(e) {})
    },

    handleMovableChange(e) {
        let currentX = this.data.currentX
        currentX[e.currentTarget.dataset.index] = e.detail.x
        this.setData({
            currentX: currentX
        })
    },

    handleTouchestart(e) {
        const that = this
        let x = this.data.x
        let currentX = this.data.currentX
        x.forEach(function(item, i) {
            if (e.currentTarget.dataset.index != i) {
                x[i] = 0
                that.setData({
                    x: x
                })
            }
        })
        currentX.forEach(function(item, i) {
            if (e.currentTarget.dataset.index != i) {
                currentX[i] = 0
                that.setData({
                    currentX: currentX
                })
            }
        })
    },

    handleTouchend: function(e) {
        let x = this.data.x
        let currentX = this.data.currentX
        if (this.data.currentX[e.currentTarget.dataset.index] < -46) {
            x[e.currentTarget.dataset.index] = -92
            this.setData({
                x: x
            })
        } else {
            x[e.currentTarget.dataset.index] = 0
            this.setData({
                x: x
            })
        }
    },

    deleteThis: function(e) {
        const that = this
        let data = {
            cart_id: e.currentTarget.dataset.id
        }
        common.post('Cart/cart_delet', data).then(function(res) {
            that.setData({
                x: [],
                currentX: []
            })
            that.getCartList()
        }).catch(function(e) {})
    },

    goGoodsDetail: function(e) {
        wx.navigateTo({
            url: '/pages/goods/goodsDetail/goodsDetail?goodsId=' + e.currentTarget.dataset.id
        })
    }
})